#include"udpserver.hpp"
#include"comm.hpp"
#include<memory>
#include<vector>
#include<cstdio>
void usage(std::string proc)
{
    std::cout <<"usage: \n\t" << proc << "local_port\n" <<std::endl;
}

std::vector<std::string> black_words={
    "rm",
     "unlink",
    "cp",
    "mv",
    "chmod",
    "exit",
    "reboot",
    "halt",
    "shutdown",
    "top",
    "kill",
    "dd",
    "vim",
    "vi",
    "nano",
    "man"
};
std::string onmessagedefault(std::string request)
{
    return request + "[haha,got you!]";
}
bool safecheck(std::string command)
{
    for(auto &k :black_words)
    {
        std::size_t pos = command.find(k);
        if(pos != std::string::npos)
        return false;
    }
    return true;
}
std::string executecommand(std::string command)
{
    if(!safecheck(command)) return "bad man";
    std::cout <<"get a message " << command << std::endl;
    FILE *fp = popen(command.c_str(),"r");
    if(fp ==nullptr)
    {
        return "execute error, reason is unknown";
    }
    std::string response;
    char buffer[1024];
    while(true)
    {
        char *s = fgets(buffer, sizeof(buffer), fp);
        if(!s) break;
        else response += buffer;
    }
    pclose(fp);
    return response.empty() ? "success" : response;
}
int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        usage(argv[0]);
        return Usage_Err;
    }
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> usvr = std::make_unique<UdpServer>(executecommand,port);
    usvr->Init();
    usvr->Start();
    return 0;
}